---
title: StreamProvider
---

import CodeBlock from "@theme/CodeBlock";
import { trimSnippet,AutoSnippet } from "../../../../../src/components/CodeSnippet";
import streamProvider from "/docs/providers/stream_provider/live_stream_chat_provider";
import streamConsumer from "!!raw-loader!/docs/providers/stream_provider/live_stream_chat_consumer.dart";

:::caution
The content of this page may be outdated.  
It will be updated in the future, but for now you may want to refer to the content
in the top of the sidebar instead (introduction/essentials/case-studies/...)
:::

`StreamProvider` is similar to [FutureProvider] but for [Stream]s instead of
[Future]s.

`StreamProvider` is usually used for:

- listening to Firebase or web-sockets
- rebuilding another provider every few seconds

Since [Stream]s naturally expose a way for listening to updates, some may think
that using `StreamProvider` has a low value. In particular, you may believe that
Flutter's [StreamBuilder] would work just as well for listening to a [Stream], but
this is a mistake.

Using `StreamProvider` over [StreamBuilder] has numerous benefits:

- it allows other providers to listen to the stream using [ref.watch].
- it ensures that loading and error cases are properly handled, thanks to [AsyncValue].
- it removes the need for having to differentiate broadcast streams vs normal streams.
- it caches the latest value emitted by the stream, ensuring that if a
  listener is added after an event is emitted, the listener will still have
  immediate access to the most up-to-date event.
- it allows easily mocking the stream during tests by overriding the `StreamProvider`.

## Usage example: live chat using sockets

`StreamProvider` is used in when we handle stream of asynchronous data
such as Video Streaming, Weather broadcasting Apis or Live chat as follows:

<AutoSnippet language="dart" {...streamProvider}></AutoSnippet>

Then, the UI can listen to live streaming chats like so:

<CodeBlock>{trimSnippet(streamConsumer)}</CodeBlock>

[ref.watch]: ../concepts/reading#using-refwatch-to-observe-a-provider
[statenotifierprovider]: ./state_notifier_provider
[provider]: ./provider
[futureprovider]: ./future_provider
[asyncvalue]: https://pub.dev/documentation/riverpod/latest/riverpod/AsyncValue-class.html
[future]: https://api.dart.dev/dart-async/Future-class.html
[stream]: https://api.dart.dev/dart-async/Stream-class.html
[stream.periodic]: https://api.dart.dev/stable/2.15.1/dart-async/Stream/Stream.periodic.html
[family]: ../concepts/modifiers/family
[streambuilder]: https://api.flutter.dev/flutter/widgets/StreamBuilder-class.html